package com.ec50n9.server.module.ebook

import com.ec50n9.server.common.render
import com.ec50n9.server.module.common.BaseService
import com.ec50n9.server.module.common.renderTo
import com.ec50n9.server.module.ebookCategory.EbookCategoryService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

interface EbookRepository : CrudRepository<Ebook, String>

@Service
class EbookService(private val ebookRepository: EbookRepository) :
    BaseService<Ebook, String>("电子书", ebookRepository)

@Tag(name = "书本管理")
@RestController
@RequestMapping("/api/ebooks")
class EbookController(
    private val ebookService: EbookService,
    private val ebookCategoryService: EbookCategoryService
) {

    @Operation(summary = "获取全部")
    @GetMapping
    fun findAll(): List<EbookListRendered> =
        ebookService.findAll().renderTo(EbookListRendered::class.java)

    @Operation(summary = "通过id获取")
    @GetMapping("/{id}")
    fun findOne(@PathVariable id: String): EbookDetailRendered =
        ebookService.findOne(id).renderTo(EbookDetailRendered::class.java)

    @Operation(summary = "新建")
    @PostMapping
    fun newOne(@RequestBody @Validated createForm: EbookCreateForm): EbookDetailRendered {
        val ebook = Ebook(createForm.name!!, ebookCategoryService.findOneByCode(createForm.categoryName!!))
        createForm.render(ebook)
        return ebookService.newOne(ebook).renderTo(EbookDetailRendered::class.java)
    }

    @Operation(summary = "更新")
    @PatchMapping("/{id}")
    fun update(@RequestBody updateForm: EbookUpdateForm, @PathVariable id: String): EbookDetailRendered {
        val ebook = ebookService.findOne(id)
        updateForm.categoryName?.let {
            ebook.category = ebookCategoryService.findOneByCode(it)
        }
        updateForm.render(ebook, true)
        return ebookService.update(ebook).renderTo(EbookDetailRendered::class.java)
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    fun delete(@PathVariable id: String) = with(ebookService) {
        delete(findOne(id))
    }
}